<template>
	<view class="customerEdit">
		<view class="container">
			<uni-list>
				<uni-list-item :clickable="true" link @click="chooseAvatar">
					<template v-slot:body>
						<button class="avatar-row">
							<view class="label">头像</view>
							<view class="avatar-box">
								<image mode="aspectFill" :src="form.avatarUrl ? form.avatarUrl : getDefaultImage()"
									@error="form.avatarUrl = getDefaultImage()" />
							</view>
						</button>
					</template>
				</uni-list-item>
				<uni-list-item>
					<template v-slot:header>
						<view class="label">客户昵称</view>
					</template>
					<template v-slot:footer>
						<input class="sign-input" placeholder="请输入客户昵称" placeholder-style="color: #bdbdbd;"
							v-model="form.username" />
					</template>
				</uni-list-item>
				<uni-list-item>
					<template v-slot:header>
						<view class="label">手机号</view>
					</template>
					<template v-slot:footer>
						<input type="number" :maxlength="11" class="sign-input" placeholder="请输入手机号"
							placeholder-style="color: #bdbdbd;" v-model="form.mobile" />
					</template>
				</uni-list-item>
				<uni-list-item>
					<template v-slot:header>
						<view class="label">公司</view>
					</template>
					<template v-slot:footer>
						<picker class="sign-input" :range="companys" range-key="name" :value="company_idx" @change="chooseCompany">
							<input placeholder="请选择公司" :value="form.company_name" placeholder-style="color: #bdbdbd;" disabled />
						</picker>
					</template>
				</uni-list-item>
				<uni-list-item>
					<template v-slot:header>
						<view class="label">职位</view>
					</template>
					<template v-slot:footer>
						<input class="sign-input" placeholder="请输入职位" placeholder-style="color: #bdbdbd;" v-model="form.position" />
					</template>
				</uni-list-item>
			</uni-list>
		</view>
		<view class="btn" @click="save">保存</view>
		<safe-area></safe-area>
	</view>
</template>

<script>
	import {
		pathToBase64,
	} from "image-tools";
	import {
		getCompanyList,
		getCustomerDetail,
	} from "@/api/search_read.js";
	import {
		customerAdd,
		customerEdit,
	} from "@/api/call_kw.js";
	import _ from "lodash";
	export default {
		data() {
			return {
				// 客户id
				id: null,
				form: {
					// 客户头像
					avatarUrl: '',
					// 客户昵称
					username: '',
					// 客户手机号
					mobile: '',
					// 客户公司
					company_id: '',
					// 客户公司名称
					company_name: '',
					// 客户职位
					position: '',
				},
				companys: [],
			}
		},
		computed: {
			// 页面类型,id存在即编辑，不存在即添加
			type() {
				return Boolean(this.id) ? 'edit' : 'add';
			},
			// 公司选中的索引
			company_idx() {
				let idx = this.companys?.findIndex(x => this.form.company_id === x.id);
				return idx > -1 ? idx : 0;
			},
		},
		onLoad(options) {
			this.id = options?.id ?? null;
			if (!this.id) {
				uni.setNavigationBarTitle({
					title: '添加客户资料'
				});
			} else {
				this.getInfo();
			}
			this.getCompanys();
		},
		methods: {
			// 获取公司列表
			getCompanys() {
				getCompanyList().then(res => {
					if (res.data?.result && res.data?.result?.length >= 1) {
						this.companys = res.data?.result?.records || [];
					}
				})
			},
			// 选择公司
			chooseCompany(e) {
				let idx = Number(e.detail.value);
				this.form.company_id = this.companys?.[idx].id || '';
				this.form.company_name = this.companys?.[idx].name || '';
			},
			// 默认头像
			getDefaultImage() {
				return require("@/static/image/avatar-default.png");
			},
			image_base64(photo) {
				return 'data:image/jpeg;base64,' + photo;
			},
			//获取客户原信息(type==='edit')
			getInfo() {
				getCustomerDetail({
					id: Number(this.id),
				}).then(res => {
					if (res.data?.result && res.data?.result?.length >= 1) {
						let info = res?.data?.result?.records?.[0] || {};
						this.form.avatarUrl = info.avatar_256 ? this.image_base64(info.avatar_256) : '';
						this.form.username = info.name || '';
						this.form.mobile = info.mobile || '';
						this.form.company_id = info.company_id?.[0] || '';
						this.form.company_name = info.company_id?.[1] || '';
						this.form.position = info.function || '';
					} else {
						uni.showToast({
							icon: 'none',
							title: res.data?.error?.data?.message || '未获取到客户信息',
						})
						uni.navigateBack();
					}
				})
			},
			//选择头像
			chooseAvatar: _.debounce(function() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const imgPath = res?.tempFilePaths[0];
						pathToBase64(imgPath).then(base64 => {
							this.form.avatarUrl = base64;
						})
					}
				})
			}, 300),
			// 点击保存
			save: _.debounce(function() {
				const showError = (msg) => {
					uni.showToast({
						icon: "none",
						title: msg,
					})
				};
				// if (!this.form.avatarUrl) {
				// 	showError('请选择头像');
				// 	return;
				// }
				if (!this.form.username) {
					showError('请输入客户昵称');
					return;
				}
				// if (!this.form.mobile) {
				// 	showError('请输入手机号');
				// 	return;
				// }
				// if (this.form.mobile.length !== 11) {
				// 	showError('请输入正确的手机号');
				// 	return;
				// }
				// if (!this.form.company_id) {
				// 	showError('请选择公司');
				// 	return;
				// }
				// if (!this.form.position) {
				// 	showError('请输入职位');
				// 	return;
				// }
				if (this.type === 'edit') {
					this.editConfirm();
				} else {
					this.addConfirm();
				}
			}, 300),
			// 编辑提交
			editConfirm() {
				uni.showLoading({
					title: '提交中...',
				})
				customerEdit({
					id: Number(this.id),
					name: this.form.username,
					mobile: this.form.mobile,
					company_id: this.form.company_id,
					function: this.form.position,
					image_1920: this.form.avatarUrl.split(',')[1],
				}).then(res => {
					if (res.data?.result) {
						uni.hideLoading();
						uni.showToast({
							icon: 'success',
							title: '编辑成功'
						})
						uni.$emit('customerChange');
						setTimeout(() => {
							uni.navigateBack();
						}, 1500)
					} else {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: res.data?.error?.data?.message || '编辑失败',
						})
					}
				}).catch(() => {
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: '系统错误',
					})
				})
			},
			// 添加提交
			addConfirm() {
				uni.showLoading({
					title: '提交中...',
				})
				customerAdd({
					name: this.form.username,
					mobile: this.form.mobile,
					company_id: this.form.company_id,
					function: this.form.position,
					image_1920: this.form.avatarUrl.split(',')[1],
				}).then(res => {
					if (res.data?.result) {
						uni.hideLoading();
						uni.showToast({
							icon: 'success',
							title: '添加成功'
						})
						uni.$emit('customerChange');
						setTimeout(() => {
							uni.navigateBack();
						}, 1500)
					} else {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: res.data?.error?.data?.message || '添加失败',
						})
					}
				}).catch(() => {
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: '系统错误',
					})
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	.customerEdit {
		width: 100%;
		height: 100%;
		background-color: white;
		display: flex;
		flex-direction: column;
		align-items: center;

		.container {
			width: 100%;
			flex: 1;
			overflow-y: auto;

			.avatar-row {
				padding: 0;
				background-color: transparent !important;
				width: 750rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				&::after {
					border: none;
				}
			}

			.label {
				margin: auto 0;
				color: black;
				font-size: 32rpx;
			}

			.avatar-box {
				width: 90rpx;
				height: 90rpx;
				border-radius: 90rpx;
				overflow: hidden;
				flex-shrink: 0;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.sign-input {
				text-align: right;
			}
		}

		.btn {
			margin: auto 0 250rpx;
			width: 380rpx;
			height: 80rpx;
			border-radius: 10rpx;
			background-color: #3F7CFB;
			line-height: 80rpx;
			text-align: center;
			color: white;
		}
	}

	/deep/.uni-list-item__container {
		padding: 36rpx 20rpx;
	}
</style>